package com.ulife.order.service.domain;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.ulife.base.entities.order.*;
import com.ulife.base.logics.order.SaleOrderItemLogic;
import com.ulife.base.logics.order.SaleOrderLogic;
import com.ulife.base.logics.order.SaleOrderPayLogic;
import com.ulife.base.logics.order.SaleOrderShipLogic;
import com.ulife.common.gateway.utils.define.Version;
import com.ulife.common.gateway.utils.entity.ServiceException;
import com.ulife.common.utils.lang.JsonMapper;
import com.ulife.member.api.MemberService;
import com.ulife.order.api.errors.OrderErrorCodes;
import com.ulife.order.api.response.*;
import com.ulife.order.service.componentConst.SaleOrderTypeConst;
import com.ulife.order.service.enumeration.SaleOrderPayStatus;
import com.ulife.order.service.enumeration.SaleOrderShipStatus;
import com.ulife.order.service.enumeration.SaleOrderStatus;
import com.ulife.order.service.strategy.ShippingFrequency;
import com.ulife.order.service.strategy.WeekShippingFrequency;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.dubbo.config.annotation.Reference;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Ulife on 2015/12/30.
 */
@Service
public class Order {

    private static JsonMapper Json = JsonMapper.nonDefaultMapper();
    Logger logger = LoggerFactory.getLogger(Order.class);

    @Resource
    SaleOrderLogic saleOrderLogic;

    @Resource
    SaleOrderItemLogic saleOrderItemLogic;

    @Resource
    SaleOrderShipLogic saleOrderShipLogic;

    @Resource
    SaleOrderPayLogic saleOrderPayLogic;

    @Reference(version = Version.LATEST)
    MemberService memberService;

    /*
    * 获取未推送订单商品预占库存
    * */
    public List<OrderSkuStock> getOrderStockHolding() {
        List<OrderSkuStock> rtn = new ArrayList<>();
        SaleOrderCriteria saleOrderCriteria = new SaleOrderCriteria();
        saleOrderCriteria.createCriteria().andStatusEqualTo(SaleOrderStatus.Created.value()).andIsDeleteEqualTo(0);
        saleOrderCriteria.or().andStatusEqualTo(SaleOrderStatus.Confirmed.value()).andIsDeleteEqualTo(0);

        List<SaleOrder> list = saleOrderLogic.list(saleOrderCriteria);
        if (list == null || list.size() == 0) return rtn;

        //key : sku id ; value : quantity
        Map<Long, Integer> map = new HashMap<>();
        for (SaleOrder saleOrder : list) {
            SaleOrderItemCriteria saleOrderItemCriteria = new SaleOrderItemCriteria();
            saleOrderItemCriteria.createCriteria().andSoNoEqualTo(saleOrder.getSaleNo());
            List<SaleOrderItem> saleOrderItemList = saleOrderItemLogic.list(saleOrderItemCriteria);
            if (saleOrderItemList == null) continue;
            for (SaleOrderItem saleOrderItem : saleOrderItemList) {
                Long key = saleOrderItem.getSkuId();
                if (map.containsKey(key)) {
                    map.put(key, map.get(key).intValue() + saleOrderItem.getQuantity());
                }
            }
        }
        if (map.size() == 0) return rtn;
        for (Long skuId : map.keySet()) {
            OrderSkuStock orderSkuStock = new OrderSkuStock();
            orderSkuStock.setSkuId(skuId);
            orderSkuStock.setQty(map.get(skuId));
            rtn.add(orderSkuStock);
        }

        return rtn;
    }


    Map<Long, Integer> defaultSku = new HashMap<Long, Integer>() {{
        put(6L, 3);
        put(7L, 2);
    }};

    /*
    * 暂停主订单配送
    * */
    public ResponseMessage suspendOrder(String orderNo, String modified_by) throws ServiceException {
        ResponseMessage responseMessage = ResponseMessage.success();

        SaleOrderCriteria criteria = new SaleOrderCriteria();
        criteria.createCriteria().andSaleNoEqualTo(orderNo).andIsDeleteEqualTo(0);
        List<SaleOrder> list = saleOrderLogic.list(criteria);
        if (list.size() <= 0) {
            throw new ServiceException(OrderErrorCodes.errorCodes_ORDER_NOT_FOUND);
        }
        SaleOrder saleOrder = list.get(0);
        if (saleOrder.getStatus() != SaleOrderStatus.Synchronized.value()) {
            throw new ServiceException(OrderErrorCodes.errorCodes_ORDER_STATUS_NOT_CORRECT);
        }

        saleOrder.setStatus(SaleOrderStatus.Suspension.value());
        saleOrder.setModifiedTime(new Date());
        saleOrder.setModifiedBy(modified_by);

        try {
            saleOrderLogic.update(saleOrder);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            responseMessage = new ResponseMessage(false, ex.getMessage());
        }
        return responseMessage;
    }

    /*
    * 批量确认子订单
    *
    * */
    public ResponseMessage confirmSubOrders(long shipping_date, String modified_by) throws ServiceException {
        ResponseMessage responseMessage = ResponseMessage.success();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date shippingDate = new Date(shipping_date);
        Calendar standardShippingDate = Calendar.getInstance();
        standardShippingDate.setTime(shippingDate);
        standardShippingDate.add(Calendar.DAY_OF_YEAR, -2);

        if (standardShippingDate.getTime().compareTo(new Date()) > 0) {//日期比较
            throw new ServiceException(OrderErrorCodes.errorCodes_ORDER_SHIPPING_DATE_ILLEGAL);
        }
        SaleOrderCriteria criteria = new SaleOrderCriteria();
        criteria.createCriteria().andShipDateEqualTo(shippingDate).andIsDeleteEqualTo(0);
        List<SaleOrder> list = saleOrderLogic.list(criteria);
        if (list == null || list.size() == 0) {
            return responseMessage;
        }

        for (SaleOrder saleOrder : list) {
            try {
                confirmSubOrder(saleOrder, modified_by);
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
        return responseMessage;
    }

    /*
    * 确认子订单
    * 1:补齐子订单菜品
    * 2:修改订单状态
    * 3:推送子订单到om系统
    * */
    private ResponseMessage confirmSubOrder(SaleOrder saleOrder, String modified_by) throws ServiceException {
        ResponseMessage responseMessage = ResponseMessage.success();

        //补齐子订单菜品
        ResponseMessage fixResult = fixSubOrderItem(saleOrder);
        if (!fixResult.isSuccess()) {
            //todo logging
            return responseMessage;
        }
        //更新订单状态
        saleOrder.setStatus(SaleOrderStatus.Confirmed.value());
        saleOrder.setModifiedBy(modified_by);
        saleOrder.setModifiedTime(new Date());

        //transaction
        try {
            saleOrderLogic.update(saleOrder);

            //推送订单到om save in queue
            syncSaleOrder(saleOrder.getSaleNo());
        } catch (Exception ex) {
            //todo logging
            //roll back
        }

        return responseMessage;
    }

    private void syncSaleOrder(String saleNo) {
        //todo
    }

    /*
    * 补齐子订单菜品
    * */
    private ResponseMessage fixSubOrderItem(SaleOrder saleOrder) {

        /*
        * 1:get parent order item
        * 2:get sub order skus' category
        * 3:statistics sub order item
        * 4:compare parent order item's sku with sub order items
        * 5:fix sku for sub order
        *
        * */

        //get parent order items
        SaleOrderItemCriteria criteria = new SaleOrderItemCriteria();
        criteria.createCriteria().andSoNoEqualTo(saleOrder.getPackageSaleNo());//sale_no = 10002
        List<SaleOrderItem> items = saleOrderItemLogic.list(criteria);

        /*SKUCriteria skuCriteria = new SKUCriteria();
        MixedSkuCriteria mixedSkuCriteria = new MixedSkuCriteria();

        SaleOrderItem mainItem = items.get(0);//[for]主单items itemid = 10
        skuCriteria.createCriteria().andIdEqualTo(Integer.parseInt(mainItem.getSkuId().toString()));//todo
        List<SKU> skus = null;//skuLogic.list(skuCriteria);
        SKU mainItemSku = skus.get(0);//[for]item skus sku_id = 8
//        if (mainItemSku.getCombination() == 1) {//是组合商品 true
        mixedSkuCriteria.createCriteria().andMixedSkuIdEqualTo((long) mainItemSku.getId());
        List<MixedSku> mixedSkus = null;//mixedSkuLogic.list(mixedSkuCriteria);
        for (MixedSku mixedSku : mixedSkus) {//组合商品sku列表 mixed_sku_id = 8==>1,2,13 base sku
            skuCriteria.createCriteria().andIdEqualTo(Integer.parseInt(mixedSku.getMixedSkuId().toString()));//todo why id is int?
            SKU mixedSkuInfo = null;//skuLogic.get(mixedSku.getId());
            if (mixedSkuInfo.getCombination() == 1) {//是组合商品 1,2,13
                mixedSkuCriteria.createCriteria().andMixedSkuIdEqualTo((long) mixedSkuInfo.getId());
                List<MixedSku> list = null;//mixedSkuLogic.list(mixedSkuCriteria);
                for (MixedSku mixed : list) {//组合商品sku列表 mixed_sku_id = 8

                }
            }
        }*/

        return null;
    }

    @Transactional
    private void createOrder(SaleOrder saleOrder, List<SaleOrderItem> saleOrderItemList, SaleOrderShip saleOrderShip) {
        saleOrderLogic.insert(saleOrder);
        saleOrderShipLogic.insert(saleOrderShip);
        for (SaleOrderItem saleOrderItem : saleOrderItemList) {
            saleOrderItemLogic.insert(saleOrderItem);
        }
    }

    /**
     * 创建子订单
     */
    public ResponseMessage CreateSubOrders(Date shipping_date) {
        ResponseMessage rtn = ResponseMessage.success();
        SaleOrderCriteria saleOrderCriteria = new SaleOrderCriteria();
        saleOrderCriteria.createCriteria().andOrderTypeEqualTo(SaleOrderTypeConst.MAIN_SALE_ORDER).andStatusBetween(SaleOrderStatus.Confirmed.value(), SaleOrderStatus.Synchronized.value()).andIsDeleteEqualTo(0);
        List<SaleOrder> saleOrders = saleOrderLogic.list(saleOrderCriteria);
        for (SaleOrder saleOrder : saleOrders) {
            try {
                String shipStrategy = saleOrder.getShipFrequency();
                ShippingFrequency shippingFrequance = null;
                //validate is in shipping frequence
                String[] strategy = shipStrategy.split(":");
                if (strategy[0].equalsIgnoreCase("week")) {
                    shippingFrequance = new WeekShippingFrequency();
                }
                if (!shippingFrequance.validate(strategy[1], shipping_date)) {//今天不配送
                    continue;
                }

                //validate shipping times
               /* SaleOrderItemCriteria saleOrderItemCriteria = new SaleOrderItemCriteria();
                saleOrderItemCriteria.createCriteria().andSoNoEqualTo(saleOrder.getSaleNo());
                List<SaleOrderItem> parentOrderItems = saleOrderItemLogic.list(saleOrderItemCriteria);
                SaleOrderItem item = parentOrderItems.get(0);

                MixedSkuCriteria mixedSkuCriteria = new MixedSkuCriteria();
                mixedSkuCriteria.createCriteria().andMixedSkuIdEqualTo(item.getSkuId());
                mixedSkuCriteria.setOrderByClause("order by multiple desc");
                List<MixedSku> mixedSkus = null;//mixedSkuLogic.list(mixedSkuCriteria);

                saleOrderCriteria.createCriteria().andPackageSaleNoEqualTo(saleOrder.getSaleNo()).andOrderTypeEqualTo(SaleOrderTypeConst.SUB_SALE_ORDER);
                List<SaleOrder> subSaleOrders = saleOrderLogic.list(saleOrderCriteria);

                if (mixedSkus.get(0).getMultiple() <= subSaleOrders.size()) {
                    logger.warn("order's sub order is finished");
                    continue;
                }*/

                ResponseMessage message = CreateSubOrder(saleOrder, null, shipping_date);
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
        return rtn;
    }


    /**
     * 创建子订单 todo need fix shipping limit item
     */
    private ResponseMessage CreateSubOrder(SaleOrder parentSaleOrder, List<SaleOrderItem> parentSaleOrderItems, Date shipping_date) throws ServiceException {
       /* ResponseMessage rtn = ResponseMessage.success();
        List<SKU> targetSKUs = new ArrayList<>();

        List<SKU> baseSKUs = new ArrayList<>();//not combination sku
        //get order items
        SaleOrderItem item = parentSaleOrderItems.get(0);
        //parse order item ==> skus
        baseSKUs.addAll(getBaseSKUs(item.getSkuId()));//may be virtual sku

        List<SKU> shippingLimitedSKUs = new ArrayList<>();
        MixedSkuShippingLimitCriteria mixedSkuShippingLimitCriteria = new MixedSkuShippingLimitCriteria();
        mixedSkuShippingLimitCriteria.createCriteria().andMixedSkuIdEqualTo(item.getSkuId());
        List<MixedSkuShippingLimit> mixedSkuShippingLimits = null;//mixedSkuShippingLimitLogic.list(mixedSkuShippingLimitCriteria);
        Map<Long, Integer> skuCategoryMap = new HashMap<>();//key=category id；value=quantity
        for (SKU sku : baseSKUs) {
            if (false) {//is in shipping limit list
                continue;
            }
            if (sku.getType()) {//是虚拟商品
                VSkuDetailCriteria vSkuDetailCriteria = new VSkuDetailCriteria();
                vSkuDetailCriteria.createCriteria().andVSkuIdEqualTo((Long) sku.getId());
                List<VSkuDetail> vSkuDetails = null;//vSkuDetailLogic.list(vSkuDetailCriteria);
                for (VSkuDetail vSkuDetail : vSkuDetails) {//category id  =  2  精品蔬菜
                    //if contained?
                    skuCategoryMap.put(vSkuDetail.getSubSkuCategory(), vSkuDetail.getSubSkuQuantity());
                }
            } else {
                targetSKUs.add(sku);
            }
        }
        Set<Long> set = skuCategoryMap.keySet();
        //处理无shipping limit 的 sku
        for (Long categoryId : set) {
            List<Long> categoryIds = getAllSubCategoryIds(categoryId);

            //构建推荐类别列表
            Map<Long, Integer> promote = new HashMap<>();
            Set<Long> promoteCategoryIds = defaultSku.keySet();
            for (Long promoteCategoryId : promoteCategoryIds) {
                if (categoryIds.contains(promoteCategoryId)) {
                    promote.put(promoteCategoryId, defaultSku.get(promoteCategoryId));
                }
            }

            int quantity = skuCategoryMap.get(categoryId);
            for (int i = 0; i < quantity; i++) {
                Set<Long> promoteIds = promote.keySet();
                for (Long promoteCategoryId : promoteIds) {//处理默认推荐的类别*数量
                    for (int j = 0; j < promote.get(promoteCategoryId); j++, i++) {
                        if (i >= quantity) break;
                        List<Long> temp = new ArrayList<>();
                        temp.add(promoteCategoryId);
                        targetSKUs.add(getRandomSku(temp));
                    }
                }

                if (i >= quantity) break;
                targetSKUs.add(getRandomSku(categoryIds));
            }
        }*/

        //get skus list
        /*Map<Long, Integer> notShipLimitMap = getSaleOrderItemCollection(parentSaleOrder, shipping_date);
        Set<Long> set = notShipLimitMap.keySet();
        CategoryCriteria categoryCriteria = new CategoryCriteria();
        List<SKU> skus = new ArrayList<>();
        for (Long key : set) {
            Category category = categoryLogic.get(Integer.parseInt(key.toString()));
            categoryCriteria.createCriteria().andParentIdEqualTo(key);
            List<Category> subCategories = categoryLogic.list(categoryCriteria);

            SKUCriteria skuCriteria = new SKUCriteria();
            skuCriteria.or().andCategoryIdEqualTo(Integer.parseInt(key.toString()));
            if (subCategories != null && subCategories.size() > 0) {
                for (Category subCategory : subCategories) {
                    skuCriteria.or().andCategoryIdEqualTo((Integer) subCategory.getId());
                }
            }
            skus.addAll(skuLogic.list(skuCriteria));
        }*/
        //create sub order
        /*List<SaleOrderItem> subSaleOrderItems = new ArrayList<>();
        for (SKU sku : targetSKUs) {
            SaleOrderItem orderItem = new SaleOrderItem();
            orderItem.setSoNo(parentSaleOrder.getSaleNo());
            orderItem.setSkuId((Long) sku.getId());
//            orderItem.setSuName(parentSaleOrderItems.get(0).getSuName());//todo
            orderItem.setSkuCategoryId((long) sku.getCategoryId());
            Category category = null;//categoryLogic.get(Long.valueOf(sku.getCategoryId()));
            orderItem.setSkuCategoryName(category.getName());
            orderItem.setQuantity(1);
            orderItem.setUnitPrice(BigDecimal.valueOf(sku.getRrp()));
            orderItem.setModifiedBy("system");
            orderItem.setModifiedTime(new Date());
            orderItem.setCreatedBy("system");
            orderItem.setCreatedTime(new Date());

            subSaleOrderItems.add(orderItem);
        }*/
        SaleOrder subSaleOrder = new SaleOrder();
        subSaleOrder.setOrderType(SaleOrderTypeConst.SUB_SALE_ORDER);
        subSaleOrder.setSaleNo(memberService.generateOrderNo());
        subSaleOrder.setPackageSaleNo(parentSaleOrder.getSaleNo());
        subSaleOrder.setCustomerId(parentSaleOrder.getCustomerId());
        subSaleOrder.setOrderTime(new Date());
        subSaleOrder.setSaleChannel(parentSaleOrder.getSaleChannel());
        subSaleOrder.setSalerId(parentSaleOrder.getSalerId());
        subSaleOrder.setSalerName(parentSaleOrder.getSalerName());
        subSaleOrder.setStatus(SaleOrderStatus.Created.value());
        subSaleOrder.setShipDate(shipping_date);
        subSaleOrder.setShipStatus(SaleOrderShipStatus.WaitShip.value());
        subSaleOrder.setPayStatus(SaleOrderPayStatus.Paid.value());
        subSaleOrder.setPayType(parentSaleOrder.getPayType());
        subSaleOrder.setPayChannel(parentSaleOrder.getPayChannel());
        subSaleOrder.setTerminal(parentSaleOrder.getTerminal());
        subSaleOrder.setSource(parentSaleOrder.getSource());
        subSaleOrder.setIsDelete( 0);
        subSaleOrder.setModifiedTime(new Date());
        subSaleOrder.setModifiedBy("system");
        subSaleOrder.setCreatedTime(new Date());
        subSaleOrder.setCreatedBy("system");
        //price is not set

        SaleOrderShipCriteria saleOrderShipCriteria = new SaleOrderShipCriteria();
        saleOrderShipCriteria.createCriteria().andSoNoEqualTo(parentSaleOrder.getSaleNo());
        List<SaleOrderShip> saleOrderShips = saleOrderShipLogic.list(saleOrderShipCriteria);

        SaleOrderShip saleOrderShip = saleOrderShips.get(0);
        SaleOrderShip subSaleOrderShip = new SaleOrderShip();
        subSaleOrderShip.setSoNo(subSaleOrder.getSaleNo());
        subSaleOrderShip.setConsignee(saleOrderShip.getConsignee());
        subSaleOrderShip.setMobile(saleOrderShip.getMobile());
        subSaleOrderShip.setPrivince(saleOrderShip.getPrivince());
        subSaleOrderShip.setCity(saleOrderShip.getCity());
        subSaleOrderShip.setCityZone(saleOrderShip.getCityZone());
        subSaleOrderShip.setDetail(saleOrderShip.getDetail());
        subSaleOrderShip.setCreatedBy("system");
        subSaleOrderShip.setCreatedTime(new Date());
        subSaleOrderShip.setModifiedBy("system");
        subSaleOrderShip.setModifiedTime(new Date());

        //begin transaction
       /* try {
            saleOrderLogic.insert(subSaleOrder);
            for (SaleOrderItem saleOrderItem : subSaleOrderItems) {
                saleOrderItemLogic.insert(saleOrderItem);
            }
            saleOrderShipLogic.insert(saleOrderShip);
        } catch (Exception ex) {
            logger.error(ex.getMessage() + "\t\t" + ex.getStackTrace());
            //todo roll back
            rtn.setIsSuccess(false);
            rtn.setMessage(ex.getMessage());
            return rtn;
        } finally {
            //todo commit
        }*/

        return null;//rtn;
    }
//    /*
//    * 生成订单号
//    * */
//    public String generateSaleNo() throws ServiceException {
//        String selectSoNo = null;
//        int i = 0;
//        do {
//            selectSoNo = soHeaderExtMapper.selectSoNo();
//            i++;
//        } while (selectSoNo == null && i < 10);
//        if (selectSoNo == null) {
////            List<String> emails = new ArrayList<String>();
////            emails.add("web_dev@u-life.cn");
////            emailService.send(emails, "订单号获取异常!", "订单号获取异常!!");
//            throw new ServiceException(OrderErrorCodes.errorCodes_GENERATER_ORDER_NO_ERROR);
//        }
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMM");
//        return simpleDateFormat.format(new Date()) + selectSoNo;
//    }

    /*
        * get random sku by category ids
        *
        * */
    /*private SKU getRandomSku(List<Long> categoryIds) {
        return null;
    }*/

    /*
        * 获取所有子类的id列表
        * */
    private List<Long> getAllSubCategoryIds(Long categoryId) {
        List<Long> rtn = new ArrayList<>();
        rtn.add(categoryId);


        return rtn;
    }

    /*
        * 获取base sku 列表
        *
        * */
   /* private List<SKU> getBaseSKUs(Long skuId) {
        List<SKU> rtn = new ArrayList<>();
        SKU sku = null;//skuLogic.get(skuId);//sku id = 8
        if (sku.getCombination() == 0) {//不是组合sku
            rtn.add(sku);
            return rtn;
        }

        MixedSkuCriteria mixedSkuCriteria = new MixedSkuCriteria();
        mixedSkuCriteria.createCriteria().andMixedSkuIdEqualTo((Long) sku.getId());
        List<MixedSku> mixedSkus = null;//mixedSkuLogic.list(mixedSkuCriteria);
        for (MixedSku mixedSku : mixedSkus) {
            rtn.addAll(getBaseSKUs(mixedSku.getBaseSkuId()));
        }
        return rtn;
    }*/

    /*
    * 取消订单
    * */
    @Transactional
    public OrderStatusInfo cancel(SaleOrder saleOrder, String operator_id) throws ServiceException {
        if (saleOrder == null || saleOrder.getPayType().isEmpty()) {
            throw new ServiceException(OrderErrorCodes.errorCodes_ORDER_CANCEL_PARAMETER_ERROR);
        }
        //判断状态 只有【创建,未支付】状态的订单才可以取消
        if (saleOrder.getStatus() != SaleOrderStatus.Created.value() && saleOrder.getPayStatus() != SaleOrderPayStatus.WaitPay.value()) {
            throw new ServiceException(OrderErrorCodes.getErrorCodes_ORDER_STATUS_ERROR);
        }
        //货到付款的订单不可取消
        if (saleOrder.getPayType().equals("货到付款")) {
            throw new ServiceException(OrderErrorCodes.getErrorCodes_ORDER_STATUS_ERROR);
        }
        /*if (saleOrder.getStatus() == SaleOrderStatus.Confirmed.value() && operator_id.equalsIgnoreCase("system"))//系统不可取消已确认订单，用户可以取消已确认订单
        {
            throw new ServiceException(OrderErrorCodes.getErrorCodes_ORDER_STATUS_ERROR);
        }*/

        //修改状态
        SaleOrder saleOrder_update = new SaleOrder();
        saleOrder_update.setId(saleOrder.getId());
        logger.info("1change sale order status from " + saleOrder_update.getStatus() + " to " + SaleOrderStatus.Cancel.value());
        saleOrder_update.setStatus(SaleOrderStatus.Cancel.value());
        saleOrder_update.setModifiedTime(new Date());
        saleOrder_update.setVersion(saleOrder.getVersion());
        if (operator_id != null && !operator_id.isEmpty()) {
            saleOrder_update.setModifiedBy(operator_id);
        } else {
            saleOrder_update.setModifiedBy("system");
        }
        saleOrderLogic.updateSelective(saleOrder_update);
        //todo refund balance
        /*SaleOrderPayCriteria saleOrderPayCriteria = new SaleOrderPayCriteria();
        saleOrderPayCriteria.createCriteria()
                .andSoNoEqualTo(saleOrder.getSaleNo())
                .andPayChannelEqualTo("Balance")
                .andStatusEqualTo(com.ulife.order.service.enumeration.SaleOrderPayStatus.Paid.value());
        List<SaleOrderPay> saleOrderPays = saleOrderPayLogic.list(saleOrderPayCriteria);
        Double refundAmount = 0d;
        if (saleOrderPays!=null&&saleOrderPays.size()>0)
        {
            for (SaleOrderPay saleOrderPay:saleOrderPays)
            {
                refundAmount += saleOrderPay.getAmount().doubleValue();
            }
        }*/

        //返回结果
        OrderStatusInfo orderStatusInfo = new OrderStatusInfo();
        orderStatusInfo.setSaleNo(saleOrder.getSaleNo());
        orderStatusInfo.setStatus(saleOrder_update.getStatus());
        return orderStatusInfo;
    }

    /*
    * 订单状态转换
    * */
    protected String OrderStatusMapping(int status, String pay_type, String orderCategory, int payStatus) {
        /*待支付：  订单类型：显示支付 && 订单状态：1 创建
        待确认：   订单类型：货到付款，未同步  ||    支付完成未同步   ||  团购订单未同步
        处理中：  拆单后到订单完结前都是处理中
        已完成：  完成
        已取消：  取消 || 部分取消
        已退款：  团购订单，支付或部分支付的单子取消
        */
        switch (status) {
            case 1:// Created
                if (pay_type.equals("线上支付")) {
                    return "待支付";
                } else if (pay_type.equals("货到付款")) {
                    return "待确认";
                } else {
                    return "";
                }
            case 2://Confirmed
                return "待确认";
            case 3:
                return "处理中";//Splited
            case 4:
                return "处理中";//Synchronized
            case 5:
                return "处理中";//Shipping
            case 6:
                return "已完成";//Rejected
            case 7://Cancel
                if (orderCategory.equals("团购订单") && (payStatus != SaleOrderPayStatus.WaitPay.value())) {
                    return "已退款";
                }
                return "已取消";
            case 8://PartialCancel
                if (orderCategory.equals("团购订单") && (payStatus != SaleOrderPayStatus.WaitPay.value())) {
                    return "已退款";
                }
                return "已取消";
            case 9:
                return "处理中";//Suspension
            case 10:
                return "已完成";//Finished
            default:
                return "";
        }
    }
    /*
        * 映射
        * */
    protected SaleOrderInfo orderInfoMapping(SaleOrder saleOrder) {
        SaleOrderInfo orderInfo = null;
        if (saleOrder == null) {
            return orderInfo;
        }
        orderInfo = new SaleOrderInfo();
        orderInfo.setOrderTime(saleOrder.getOrderTime().getTime());
        orderInfo.setSaleNo(saleOrder.getSaleNo());
        orderInfo.setShipDate(saleOrder.getShipDate().getTime());
        orderInfo.setOrderCategory(saleOrder.getOrderCategory());
        orderInfo.setGroupId(saleOrder.getGroupId());
        orderInfo.setPayStatus(saleOrder.getPayStatus());
        orderInfo.setPayType(saleOrder.getPayType());
        orderInfo.setSubAmount(saleOrder.getSubAmount().doubleValue());
        orderInfo.setPromotionDiscount(saleOrder.getPromotionDiscount().doubleValue());
        orderInfo.setProductCouponDiscount(saleOrder.getProductCouponDiscount().doubleValue());
        orderInfo.setShipFee(saleOrder.getShipFee().doubleValue());
        orderInfo.setShipFeeDiscount(saleOrder.getShipFeeDiscount().doubleValue());
        orderInfo.setShipFeeCouponDiscount(saleOrder.getShipFeeCouponDiscount().doubleValue());
        orderInfo.setTotalAmount(saleOrder.getTotalAmount().doubleValue());
        orderInfo.setPaidAmount(saleOrder.getPaidAmount().doubleValue());
        orderInfo.setCreatedBy(saleOrder.getCreatedBy());
        orderInfo.setStatus(saleOrder.getStatus());
        orderInfo.setStatusValue(OrderStatusMapping(saleOrder.getStatus(), saleOrder.getPayType(), saleOrder.getOrderCategory(), saleOrder.getPayStatus()));
        return orderInfo;
    }
}